import { login, loginByPhone, sendSmsCode } from '@/api/user'

export default {
  namespaced: true,
  state: {
    token: '',
    userInfo: null
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_INFO: (state, info) => {
      state.userInfo = info
    }
  },
  actions: {
    // 账号密码登录
    async login({ commit }, userInfo) {
      try {
        const { data } = await login(userInfo)
        commit('SET_TOKEN', data.token)
        commit('SET_USER_INFO', data.userInfo)
        return data
      } catch (error) {
        throw error
      }
    },

    // 手机验证码登录
    async loginByPhone({ commit }, phoneInfo) {
      try {
        const { data } = await loginByPhone(phoneInfo)
        commit('SET_TOKEN', data.token)
        commit('SET_USER_INFO', data.userInfo)
        return data
      } catch (error) {
        throw error
      }
    },

    // 发送短信验证码
    async sendSmsCode(_, phone) {
      try {
        const { data } = await sendSmsCode(phone)
        return data
      } catch (error) {
        throw error
      }
    },

    // 退出登录
    logout({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', null)
    }
  }
}
